/**
 * 
 */
package easytalk.connectivity.msn;

import net.sf.jml.MsnContact;
import net.sf.jml.MsnContactList;
import net.sf.jml.MsnMessenger;
import net.sf.jml.MsnProtocol;
import net.sf.jml.MsnUserStatus;
import net.sf.jml.event.MsnContactListAdapter;
import net.sf.jml.event.MsnMessageAdapter;
import net.sf.jml.impl.MsnMessengerFactory;

import common.BodySet;
import common.DiscussionSentence;
import common.EasyChatEnvironment;
import common.Locutor;

import connection.AbstarctServerConnection;
import connection.ServerType;

/**
 * @author bacem
 * 
 */
public class MsnConnection extends AbstarctServerConnection {

	MsnMessenger messenger;
	BodySet set;
	private String name;
	
	public MsnConnection() {

	}

	@Override
	public void hookBodySet(BodySet nset) throws Exception {

		this.set = nset;
		System.out.println("MsnConnection.hookBodySet()");
		messenger.addContactListListener(new MsnContactListAdapter() {
		
			@Override
			public void contactListInitCompleted(MsnMessenger arg0) {
				System.out.println(".contactListInitCompleted()");
				logWriter.write("updating contact list");
				MsnContactList contactList = messenger.getContactList();
				for (MsnContact contact : contactList.getContacts()) {
					Locutor locutor = set.createLocutor(contact.getId());
					locutor.setName(contact.getDisplayName());
					
					// set.addLocutor(locutor);
				}
				setName(messenger.getOwner().getDisplayName());
				EasyChatEnvironment.getInstance().update();
			}

		});
		messenger.addMessageListener(new MsnMessageAdapter() {
			
		});
	}

	@Override
	public boolean login(String username, String password) throws Exception {

		
		this.config.setServerType(ServerType.MSN);
		this.config.setUserName(username);
		this.config.setPassword(password);
		
		messenger = MsnMessengerFactory.createMsnMessenger(username, password);
		logWriter.write("creating connection");
		messenger.setSupportedProtocol(new MsnProtocol[] { MsnProtocol.MSNP11 });
		messenger.getOwner().setInitStatus(MsnUserStatus.ONLINE);
		messenger.setLogIncoming(true);
		messenger.setLogOutgoing(true);
		logWriter.write("logging in");
		messenger.login();
		logWriter.write("logged");
		
		return true;
	}

	@Override
	public void logout() {
			messenger.logout();
	}

	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void createChat(String id) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void sendMessage(String id, DiscussionSentence sentence) {
		// TODO Auto-generated method stub
		
	}

}
